package com.css.zfzx.sjcj.modules.yhdisaster.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.role.repository.entity.RoleEntity;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.CommonConstant;
import com.css.zfzx.sjcj.common.utils.*;
import com.css.zfzx.sjcj.modules.boundary.service.BoundaryService;
import com.css.zfzx.sjcj.modules.yhdisaster.params.ExportDisasterEvaluateParams;
import com.css.zfzx.sjcj.modules.yhdisaster.repository.YhDisasterNativeRepository;
import com.css.zfzx.sjcj.modules.yhdisaster.repository.YhDisasterRepository;
import com.css.zfzx.sjcj.modules.yhdisaster.repository.entity.AssessEntity.*;
import com.css.zfzx.sjcj.modules.yhdisaster.repository.entity.YhDisasterEntity;
import com.css.zfzx.sjcj.modules.yhdisaster.repository.entity.YhDisasterEvaluateVO;
import com.css.zfzx.sjcj.modules.yhdisaster.repository.vo.EvaluateResultVo;
import com.css.zfzx.sjcj.modules.yhdisaster.service.YhDisasterService;
import com.css.zfzx.sjcj.modules.yhdisaster.viewobjects.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lxg
 * @date 2020-11-10
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class YhDisasterServiceImpl implements YhDisasterService {

    private static final Logger logger = LoggerFactory.getLogger(YhDisasterServiceImpl.class);

    private final YhDisasterRepository yhDisasterRepository;
    private final YhDisasterNativeRepository yhDisasterNativeRepository;
    private final DisasterEvaluationExportServer disasterEvaluationExportServer;
    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    public YhDisasterServiceImpl(YhDisasterRepository yhDisasterRepository,
                                 YhDisasterNativeRepository yhDisasterNativeRepository,
                                 DisasterEvaluationExportServer disasterEvaluationExportServer) {
        this.yhDisasterRepository = yhDisasterRepository;
        this.yhDisasterNativeRepository = yhDisasterNativeRepository;
        this.disasterEvaluationExportServer = disasterEvaluationExportServer;
    }

    @Value("${transactional.commit.size:10000}")
    private int commitSize;

    @Override
    public JSONObject queryYhDisasters(YhDisasterQueryParams queryParams, int curPage, int pageSize, String type, String sort, String order) {
        if (!PlatformObjectUtils.isEmpty(sort) && sort.length() > 0) {
            sort = CheckObjFields.propertyChange(sort);
        }
        Page<YhDisasterEntity> yhDisasterPage = this.yhDisasterNativeRepository.queryYhDisasters(queryParams, curPage, pageSize, type, sort, order);
        return PlatformPageUtils.formatPageData(yhDisasterPage);
    }


    @Override
    public YhDisasterEntity getYhDisaster(String id) {
        return this.yhDisasterRepository.findById(id).orElse(null);
    }

    @Override
    public YhDisasterEntity getYhDisaster(String id, String province) {
        String provinceSubfix = buildProvinceSubfix(province);
        String sql = "select * from yh_disaster" + provinceSubfix + " where id='" + id + "' and is_valid=1";
        Query query = entityManager.createNativeQuery(sql, YhDisasterEntity.class);
        return ((YhDisasterEntity) query.getResultList().get(0));
    }

    //    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public YhDisasterEntity saveYhDisaster(YhDisasterEntity yhDisaster, String type) {
//        String uuid = UUIDGenerator.getUUID();
//        yhDisaster.setId(uuid);
//        yhDisaster.setCreateUserId(PlatformSessionUtils.getUserId());
//        yhDisaster.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
//        yhDisaster.setIsValid("1");
//        yhDisaster.setYhProjectType(type);
//        yhDisaster.setReviewStatus("0");
//        this.yhDisasterRepository.save(yhDisaster);
//        return yhDisaster;
//    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public YhDisasterEntity saveYhDisaster(YhDisasterEntity yhDisaster, String type) {
        StringBuilder builder = new StringBuilder();
        String provinceSubfix = buildProvinceSubfix(yhDisaster.getProvince());
        String uuid = UUIDGenerator.getUUID();
        yhDisaster.setId(uuid);
        yhDisaster.setCreateUserId(PlatformSessionUtils.getUserId());
        yhDisaster.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        yhDisaster.setIsValid("1");
        yhDisaster.setYhProjectType(type);
        yhDisaster.setReviewStatus("0");
        builder.append("INSERT INTO yh_disaster").append(provinceSubfix).append("(");

        //构建insert操作的拼接的sql
        String buildSql = buildInsertFieldSql(yhDisaster);
        if (StringUtils.isNotBlank(buildSql)) {
            String fieldSql = buildSql.split("@")[0];
            String valueSql = buildSql.split("@")[1];
            builder.append(fieldSql).append(" ) values(");
            builder.append(valueSql).append(")");
        }
        Query query = entityManager.createNativeQuery(builder.toString());
        int i = query.executeUpdate();
        return yhDisaster;
    }

    private String buildInsertFieldSql(YhDisasterEntity yhDisaster) {
        StringBuilder fieldBuilder = new StringBuilder("");
        StringBuilder fieldValueBuilder = new StringBuilder("");
        Field[] fields = ReflectUtil.getFields(yhDisaster.getClass());
        AtomicInteger integer = new AtomicInteger(0);
        for (Field field : fields) {
            Class<?> type = field.getType();
            field.setAccessible(true);
            String name = field.getName();
            name = StringUtil.humpToUnderline(name);
            fieldBuilder.append(name);
            Object value = ReflectUtil.getFieldValue(yhDisaster, field);
            if (type.getName().equals("java.util.Date")) {
                value = (value == null ? null : "'" + value + "'");
            } else {
                value = (value == null ? "''" : "'" + value + "'");
            }

            fieldValueBuilder.append(value);
            if (integer.get() < fields.length - 1) {
                fieldBuilder.append(",");
                fieldValueBuilder.append(",");
            }
            integer.getAndIncrement();
        }
        return (fieldBuilder.append("@").append(fieldValueBuilder)).toString();
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public YhDisasterEntity updateYhDisaster(YhDisasterEntity yhDisaster) {
//        YhDisasterEntity yhDisasterEntity = yhDisasterRepository.findById(yhDisaster.getId()).get();
//        UpdateUtil.copyNullProperties(yhDisasterEntity, yhDisaster);
//        String userId = PlatformSessionUtils.getUserId();
//        List<RoleEntity> roleList = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
//        for (RoleEntity roles : roleList) {
//            if (roles.getRoleName().equals("普通质检员")) {
//                yhDisaster.setQualityinspectionStatus("1");
//            } else if (roles.getRoleName().equals("终检质检员")) {
//                yhDisaster.setQualityinspectionStatus("2");
//            }
//        }
//        yhDisaster.setEvaluationResult("1");
//        yhDisaster.setUpdateUser(userId);
//        yhDisaster.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
//        this.yhDisasterRepository.save(yhDisaster);
//        return yhDisaster;
//    }
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public YhDisasterEntity updateYhDisaster(YhDisasterEntity yhDisaster) {
//        String provinceSubfix = buildProvinceSubfix(yhDisaster.getProvince());
//        YhDisasterEntity yhDisasterEntity = null;
//        String findByIdAndIsValidAndProvinceSql = "select * from yh_disaster"+provinceSubfix+" where id ='"+yhDisaster.getId()+"' AND is_valid='1'";
//        Query findByIdAndIsValidAndProvinceQuery = entityManager.createNativeQuery(findByIdAndIsValidAndProvinceSql,YhDisasterEntity.class);
//        yhDisasterEntity =(YhDisasterEntity) findByIdAndIsValidAndProvinceQuery.getSingleResult();
//        UpdateUtil.copyNullProperties(yhDisasterEntity, yhDisaster);
//        String userId = PlatformSessionUtils.getUserId();
//        List<RoleEntity> roleList = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
//        for (RoleEntity roles : roleList) {
//            if (roles.getRoleName().equals("普通质检员")) {
//                yhDisaster.setQualityinspectionStatus("1");
//            } else if (roles.getRoleName().equals("终检质检员")) {
//                yhDisaster.setQualityinspectionStatus("2");
//            }
//        }
//        yhDisaster.setEvaluationResult("1");
//        yhDisaster.setUpdateUser(userId);
//        yhDisaster.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
//
//        StringBuilder builder = new StringBuilder();
//        builder.append("update yh_disaster").append(provinceSubfix).append(" set ");
//        YhDisasterEntity1 disasterEntity = getChildisasterEntity(yhDisaster);
//        //构建update操作的拼接的sql
//        String buildSql = buildUpdateFieldSql(disasterEntity);
//        builder.append(buildSql);
//        Query query = entityManager.createNativeQuery(builder.toString());
//        int i = query.executeUpdate();
//        return yhDisaster;
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public YhDisasterEntity updateYhDisaster(YhDisasterEntity yhDisaster) {
        String provinceSubfix = buildProvinceSubfix(yhDisaster.getProvince());
        StringBuilder builder = new StringBuilder();
        builder.append("update yh_disaster").append(provinceSubfix).append(" set ");
        String userId = PlatformSessionUtils.getUserId();
        List<RoleEntity> roleList = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        for (RoleEntity roles : roleList) {
            if (roles.getRoleName().equals("普通质检员")) {
                builder.append("qualityinspection_status=1,");
            } else if (roles.getRoleName().equals("终检质检员")) {
                builder.append("qualityinspection_status=2,");
            }
        }
        builder.append(" evaluation_result=1 ,");
        builder.append(" update_time=").append(PlatformDateUtils.getCurrentTimestamp()).append(",");
        builder.append(" update_user=").append(userId);
        Query query = entityManager.createNativeQuery(builder.toString());
        int i = query.executeUpdate();
        return yhDisaster;
    }

    //    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void deleteYhDisasters(List<String> ids) {
//        List<YhDisasterEntity> yhDisasterList = this.yhDisasterRepository.findAllById(ids);
//        if (!PlatformObjectUtils.isEmpty(yhDisasterList) && yhDisasterList.size() > 0) {
//            for (YhDisasterEntity yhDisaster : yhDisasterList) {
//                yhDisaster.setIsValid(PlatformConstants.N);
//                this.yhDisasterRepository.save(yhDisaster);
//            }
//        }
//    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteYhDisasters(List<String> ids) {
        List<String> idList = new ArrayList<>(ids.size());
        ids.forEach(id -> {
            idList.add(id.split("_")[0]);
        });
        //删除时只能按照某省删除
        String provinceSubfix = buildProvinceSubfix(ids.get(0).split("_")[1]);
//        String findByIdAndIsValidAndProvinceSql = "select * from yh_disaster"+provinceSubfix+" where id in ("+idList+") AND is_valid='1'";
//        Query findByIdAndIsValidAndProvinceQuery = entityManager.createNativeQuery(findByIdAndIsValidAndProvinceSql,YhDisasterEntity.class);
//        List yhDisasterList = findByIdAndIsValidAndProvinceQuery.getResultList();
//        if (!PlatformObjectUtils.isEmpty(yhDisasterList) && yhDisasterList.size() > 0) {
//            for (Object obj : yhDisasterList) {
//                if(obj instanceof YhDisasterEntity){
//                    YhDisasterEntity yhDisaster = (YhDisasterEntity) obj;
//                    yhDisaster.setIsValid(PlatformConstants.N);
        //this.yhDisasterRepository.save(yhDisaster);

        StringBuilder builder = new StringBuilder();
        builder.append("update yh_disaster").append(provinceSubfix).append(" set is_valid=0");
        builder.append(" where id in (").append(idList).append(")");
        //构建delete操作的拼接的sql
//            String buildSql = buildDeleteFieldSql(yhDisaster);
//            builder.append(buildSql);
        Query query = entityManager.createNativeQuery(builder.toString());
        query.executeUpdate();
//                }
//            }
        //}
    }

    private String buildDeleteFieldSql(YhDisasterEntity yhDisaster) {
        StringBuilder fieldBuilder = new StringBuilder("");
        Field[] fields = ReflectUtil.getFields(yhDisaster.getClass());
        AtomicInteger integer = new AtomicInteger(0);
        String idValue = "";
        for (Field field : fields) {
            Class<?> type = field.getType();
            field.setAccessible(true);
            String name = field.getName();
            Object value = ReflectUtil.getFieldValue(yhDisaster, field);
            name = StringUtil.humpToUnderline(name);
            if ("id".equals(name)) {
                idValue = (String) value;
                continue;
            }
            fieldBuilder.append(name).append("=");
            if (type.getName().equals("java.util.Date")) {
                SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                value = (value == null ? null : "'" + Timestamp.valueOf(simpleDate.format(value)) + "'");

            } else {
                value = (value == null ? "''" : "'" + value + "'");
            }
            fieldBuilder.append(value);
            if (integer.get() < fields.length - 1) {
                fieldBuilder.append(",");
            }
        }
        String s = fieldBuilder.toString();
        if (s.charAt(s.length() - 1) == ',') { //s.length()-1获取字符串最后一位字符的索引，传入charAt方法获取索引对应的字符，判断是否为逗号
            s = s.substring(0, s.length() - 1);
        }
        String whereSql = " where id= '" + idValue + "'";
        return s + whereSql;
    }


    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(2);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<YhDisasterVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), YhDisasterVO.class, params);
            List<YhDisasterVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            // 业务主键不存在的条数
            int failCount = saveDisasterList(list, sb);
            if (failCount > 0) {
                // result.getFailList().size()为保存时出错的条数
                int failList = firstList + result.getFailList().size() - list.size();
                returnMsg.append("成功导入").append(result.getList().size() - failCount).append("条，失败").append(failList + failCount).append("条<br/>");
                returnMsg.append("业务主键").append(failCount).append("不存在的数据<br/>");
                returnMsg.append(sb);
            } else {
                returnMsg.append("成功导入" + (result.getList().size() - failCount) + "条，失败" + (result.getFailList().size() + failCount) + "条<br/>");
                returnMsg.append(sb);
            }
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (YhDisasterVO yhDisasterVO : result.getFailList()) {
                    String error = "";
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public void submitYhDisaster(String ids) {
        String[] split = ids.split(",");
        List<String> list = new ArrayList<>(Arrays.asList(split));
        List<YhDisasterEntity> yhDisasterEntities = yhDisasterRepository.findAllById(list);
        for (YhDisasterEntity entity : yhDisasterEntities) {
            entity.setReviewStatus("1");
            yhDisasterRepository.save(entity);
        }
    }

    @Override
    public void submitYhDisaster(List<YhDisasterEntity> disasterEntities) {
        String provinceSubfix = buildProvinceSubfix(disasterEntities.get(0).getProvince());
        disasterEntities.forEach(yhDisasterEntity -> {
            Query query = entityManager.createNativeQuery("update yh_disaster" + provinceSubfix + " set review_status = 1 where id=" + yhDisasterEntity.getId());
            query.executeUpdate();
        });
    }

    @Override
    public void exportFile(YhDisasterQueryParams queryParams, String type, HttpServletResponse response) {
        List<YhDisasterEntity> yhDisasterEntities = yhDisasterNativeRepository.exportYhDisasters(queryParams, type);
        List<YhDisasterVO> list = new ArrayList<>();
        for (YhDisasterEntity entity : yhDisasterEntities) {
            String extends1 = entity.getExtends1();
            if (!StringUtils.isEmpty(extends1)) {
                switch (extends1) {
                    case CommonConstant.TYPE_CITY_HOUSE_CH:
                        extends1 = CommonConstant.TYPE_CITY_HOUSE_DISC;
                        break;
                    case CommonConstant.TYPE_CITY_NO_HOUSE_CH:
                        extends1 = CommonConstant.TYPE_CITY_NO_HOUSE_DISC;
                        break;
                    case CommonConstant.TYPE_COUNTRY_JH_HOUSE_CH:
                        extends1 = CommonConstant.TYPE_COUNTRY_JH_HOUSE_DISC;
                        break;
                    case CommonConstant.TYPE_COUNTRY_DL_HOUSE_CH:
                        extends1 = CommonConstant.TYPE_COUNTRY_DL_HOUSE_DISC;
                        break;
                    case CommonConstant.TYPE_COUNTRY_NO_HOUSE_CH:
                        extends1 = CommonConstant.TYPE_COUNTRY_NO_HOUSE_DISC;
                        break;
                    case CommonConstant.TYPE_BRIDGE_CH:
                        extends1 = CommonConstant.TYPE_BRIDGE_DISC;
                        break;
                    case CommonConstant.TYPE_WATER_FACTILITY_CH:
                        extends1 = CommonConstant.TYPE_WATER_FACTILITY_DISC;
                        break;
                }
                entity.setExtends1(extends1);
            }
            YhDisasterVO yhDisasterVO = new YhDisasterVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "重点隐患数据", "重点隐患数据", YhDisasterVO.class, "重点隐患数据.xls", response);
    }

    private YhDisasterEntity1 getChildisasterEntity(YhDisasterEntity entity) {
        String pinyinOfProvince = "";
        if (org.apache.commons.lang.StringUtils.isNotBlank(entity.getProvince())) {
            pinyinOfProvince = PinyinUtil.getPinyin(entity.getProvince());
            if ("山西省".equals(entity.getProvince())) {
                pinyinOfProvince = (pinyinOfProvince + "1");
            }
        }
        switch (pinyinOfProvince) {
            case "beijingshi":
                return new YhDisaster11Entity();
            case "tianjinshi":
                return new YhDisaster12Entity();
            case "shanghaishi":
                return new YhDisaster31Entity();
            case "chongqingshi":
                return new YhDisaster50Entity();
            case "heilongjiangsheng":
                return new YhDisaster23Entity();
            case "jilinsheng":
                return new YhDisaster22Entity();
            case "liaoningsheng":
                return new YhDisaster21Entity();
            case "anhuisheng":
                return new YhDisaster34Entity();
            case "fujiansheng":
                return new YhDisaster35Entity();
            case "gansusheng":
                return new YhDisaster62Entity();
            case "guangdongsheng":
                return new YhDisaster44Entity();
            case "guangxizhuangzuzizhiqu":
                return new YhDisaster45Entity();
            case "guizhousheng":
                return new YhDisaster52Entity();
            case "hainansheng":
                return new YhDisaster46Entity();
            case "hebeisheng":
                return new YhDisaster13Entity();
            case "henansheng":
                return new YhDisaster41Entity();
            case "hubeisheng":
                return new YhDisaster42Entity();
            case "hunansheng":
                return new YhDisaster43Entity();
            case "jiangsusheng":
                return new YhDisaster32Entity();
            case "jiangxisheng":
                return new YhDisaster36Entity();
            case "neimengguzizhiqu":
                return new YhDisaster15Entity();
            case "ningxiahuizuzizhiqu":
                return new YhDisaster64Entity();
            case "qinghaisheng":
                return new YhDisaster63Entity();
            case "shandongsheng":
                return new YhDisaster37Entity();
            case "shanxisheng":
                return new YhDisaster61Entity();
            case "shanxisheng1":
                return new YhDisaster14Entity();
            case "sichuansheng":
                return new YhDisaster51Entity();
//            case "taiwansheng":
//                return new YhTaiwanDisasterUpdateVo();
            case "xinjiangweiwuerzizhiqu":
                return new YhDisaster65Entity();
            case "xizangzizhiqu":
                return new YhDisaster54Entity();
            case "yunnansheng":
                return new YhDisaster53Entity();
            case "zhejiangsheng":
                return new YhDisaster33Entity();
            case "xinjiangshengchanjianshebingtuan":
                return new YhDisaster66Entity();
//            case "xianggangtebiexingzhengqu":
//                return new YhXianggangDisasterUpdateVo();
//            case "aomentebiexingzhengqu":
//                return new YhAomenDisasterUpdateVo();
            default:
                return new YhDisaster11Entity();
        }
    }

    @Override
    public void assessmentInfo(String type, YhDisasterQueryParams queryParams) {
        List<YhDisasterEntity> yhDisasterEntities = yhDisasterNativeRepository.exportYhDisasters(queryParams, type);
        List<YhDisasterEntity1> yhList = new ArrayList<>();
        for (YhDisasterEntity entities : yhDisasterEntities) {
            YhDisasterEntity1 disasterEntity = getChildisasterEntity(entities);
            BeanUtils.copyProperties(entities, disasterEntity);
            EvaluateResultVo evaluateResultVo = pgResult(entities);
            disasterEntity.setEvaluationResult(evaluateResultVo.getResult());
            disasterEntity.setCvalue(evaluateResultVo.getCvalue());
            disasterEntity.setRvalue(evaluateResultVo.getRvalue());
            disasterEntity.setVvalue(evaluateResultVo.getVvalue());
            disasterEntity.setPheq(evaluateResultVo.getPHEQ());
            disasterEntity.setIsUpToStandard(evaluateResultVo.getIsUpToStandard());
            disasterEntity.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            //yhDisasterRepository.save(entities);
            yhList.add(disasterEntity);
        }
        if (yhList.size() < commitSize) {
            yhDisasterNativeRepository.batchUpdate(yhList);
        } else {
            int size = yhList.size() / commitSize;
            if (yhList.size() % commitSize != 0) {
                size++;
            }
            for (int i = 0; i < size; i++) {
                List<YhDisasterEntity1> subList = new ArrayList<>();
                if ((i + 1) * commitSize > yhList.size()) {
                    subList = yhList.subList(i * commitSize, yhList.size());
                    System.out.println("===========当前提交数据位置:  " + yhList.size());
                } else {
                    subList = yhList.subList(i * commitSize, (i + 1) * commitSize);
                    System.out.println("===========当前提交数据位置:  " + (i + 1) * commitSize);
                }
                yhDisasterNativeRepository.batchUpdate(subList);
            }
        }
    }

//    @Override
//    public void assessmentInfoBak(String type, YhDisasterQueryParams queryParams) {
//        List<YhDisasterEntity> yhDisasterEntities = yhDisasterNativeRepository.exportYhDisasters(queryParams, type);
//        List<YhDisasterEntity> yhList = new ArrayList<>();
//        for (YhDisasterEntity entities : yhDisasterEntities) {
//            EvaluateResultVo evaluateResultVo = pgResult(entities);
//            entities.setEvaluationResult(evaluateResultVo.getResult());
//            entities.setCvalue(evaluateResultVo.getCvalue());
//            entities.setRvalue(evaluateResultVo.getRvalue());
//            entities.setVvalue(evaluateResultVo.getVvalue());
//            entities.setPHEQ(evaluateResultVo.getPHEQ());
//            entities.setIsUpToStandard(evaluateResultVo.getIsUpToStandard());
//            entities.setUpdateTime(new Timestamp(System.currentTimeMillis()));
//            //yhDisasterRepository.save(entities);
//            yhList.add(entities);
//        }
//        if (yhList.size() < commitSize) {
//            yhDisasterNativeRepository.batchUpdate(yhList);
//        } else {
//            int size = yhList.size() / commitSize;
//            if (yhList.size() % commitSize != 0) {
//                size++;
//            }
//            for (int i = 0; i < size; i++) {
//                List<YhDisasterEntity> subList = new ArrayList<>();
//                if ((i + 1) * commitSize > yhList.size()) {
//                    subList = yhList.subList(i * commitSize, yhList.size());
//                    System.out.println("===========当前提交数据位置:  " + yhList.size());
//                } else {
//                    subList = yhList.subList(i * commitSize, (i + 1) * commitSize);
//                    System.out.println("===========当前提交数据位置:  " + (i + 1) * commitSize);
//                }
//                yhDisasterNativeRepository.batchUpdate(subList);
//            }
//        }
//    }

    /**
     * 获取各省表的后缀
     */
    private String buildProvinceSubfix(String province) {
        String pinyinOfProvince = "";
        if (org.apache.commons.lang.StringUtils.isNotBlank(province)) {
            pinyinOfProvince = PinyinUtil.getPinyin(province);
            if ("山西省".equals(province)) {
                pinyinOfProvince = (pinyinOfProvince + "1");
            }
            pinyinOfProvince = ("_" + pinyinOfProvince);
        }
        return pinyinOfProvince;
    }

    @Override
    public void autoAssessment(String ids) {
        String[] split = ids.split(",");
        List<String> list = new ArrayList<>(Arrays.asList(split));
        List<YhDisasterEntity> yhDisasterEntities = yhDisasterRepository.findAllById(list);
        for (YhDisasterEntity entities : yhDisasterEntities) {
            YhDisasterEntity1 disasterEntity = getChildisasterEntity(entities);
            String provinceSubfix = buildProvinceSubfix(entities.getProvince());
            EvaluateResultVo evaluateResultVo = pgResult(entities);
            entities.setEvaluationResult(evaluateResultVo.getResult());
            entities.setCvalue(evaluateResultVo.getCvalue());
            entities.setRvalue(evaluateResultVo.getRvalue());
            entities.setVvalue(evaluateResultVo.getVvalue());
            entities.setPHEQ(evaluateResultVo.getPHEQ());
            entities.setIsUpToStandard(evaluateResultVo.getIsUpToStandard());
            entities.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            BeanUtils.copyProperties(entities, disasterEntity);
            disasterEntity.setPheq(entities.getPHEQ());
            StringBuilder builder = new StringBuilder();
            builder.append("update yh_disaster").append(provinceSubfix).append(" set ");
            //构建delete操作的拼接的sql
            String buildSql = buildUpdateFieldSql(disasterEntity);
            builder.append(buildSql);
            Query query = entityManager.createNativeQuery(builder.toString());
            int i = query.executeUpdate();
        }
    }

    @Override
    public void autoAssessment(YhDisasterEvaluateVO vo) {
        String provinceSubfix = buildProvinceSubfix(vo.getProvince());
        String[] split = vo.getYhDisasterId().split(",");
        String insql = buildInSql(split);
        String sql = "select * from yh_disaster" + provinceSubfix + " where is_valid='1' and id in (" + insql + ")";
        Query query1 = entityManager.createNativeQuery(sql, YhDisasterEntity.class);
        List<YhDisasterEntity> resultList = query1.getResultList();
        //List<YhDisasterEntity> yhDisasterEntities = yhDisasterRepository.findAllById(list);
        for (YhDisasterEntity entities : resultList) {
            //if(obj instanceof YhDisasterEntity){
            //YhDisasterEntity entities = (YhDisasterEntity) obj;
            YhDisasterEntity1 disasterEntity = getChildisasterEntity(entities);
            EvaluateResultVo evaluateResultVo = pgResult(entities);
            BeanUtils.copyProperties(entities, disasterEntity);
            disasterEntity.setEvaluationResult(evaluateResultVo.getResult());
            disasterEntity.setCvalue(evaluateResultVo.getCvalue());
            disasterEntity.setRvalue(evaluateResultVo.getRvalue());
            disasterEntity.setVvalue(evaluateResultVo.getVvalue());
            disasterEntity.setPheq(evaluateResultVo.getPHEQ());
            disasterEntity.setIsUpToStandard(evaluateResultVo.getIsUpToStandard());
            disasterEntity.setUpdateTime(new Timestamp(System.currentTimeMillis()));

            //disasterEntity.setPheq(entities.getPHEQ());
            StringBuilder builder = new StringBuilder();
            builder.append("update yh_disaster").append(provinceSubfix).append(" set ");
            //构建Update操作的拼接的sql
            String buildSql = buildUpdateFieldSql(disasterEntity);
            builder.append(buildSql);
            Query query = entityManager.createNativeQuery(builder.toString());
            int i = query.executeUpdate();
            //}
        }
    }

    private String buildInSql(String[] split) {
        // '','',''
        StringBuilder builder = new StringBuilder();
        if (split != null && split.length > 0) {
            for (String s : split) {
                builder.append("'").append(s).append("',");
            }
        }
        return builder.substring(0, builder.length() - 1).toString();
    }

    private String buildUpdateFieldSql(YhDisasterEntity1 yhDisaster) {
        StringBuilder fieldBuilder = new StringBuilder("");
        Field[] fields = ReflectUtil.getFields(yhDisaster.getClass());
        AtomicInteger integer = new AtomicInteger(0);
        String idValue = "";
        for (Field field : fields) {
            Class<?> type = field.getType();
            field.setAccessible(true);
            String name = field.getName();
            Object value = ReflectUtil.getFieldValue(yhDisaster, field);
            name = StringUtil.humpToUnderline(name);
            if ("id".equals(name)) {
                idValue = (String) value;
                continue;
            }
            fieldBuilder.append(name).append("=");
            if (type.getName().equals("java.util.Date")) {
                SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                value = (value == null ? null : "'" + Timestamp.valueOf(simpleDate.format(value)) + "'");

            } else {
                value = (value == null ? "''" : "'" + value + "'");
            }
            fieldBuilder.append(value);
            if (integer.get() < fields.length - 1) {
                fieldBuilder.append(",");
            }
        }
        String s = fieldBuilder.toString();
        if (s.charAt(s.length() - 1) == ',') { //s.length()-1获取字符串最后一位字符的索引，传入charAt方法获取索引对应的字符，判断是否为逗号
            s = s.substring(0, s.length() - 1);
        }
        String whereSql = " where id= '" + idValue + "'";
        return s + whereSql;
    }

//    @Override
//    public void autoAssessmentBak(String ids) {
//        String[] split = ids.split(",");
//        List<String> list = new ArrayList<>(Arrays.asList(split));
//        List<YhDisasterEntity> yhDisasterEntities = yhDisasterRepository.findAllById(list);
//        for (YhDisasterEntity entities : yhDisasterEntities) {
//            EvaluateResultVo evaluateResultVo = pgResult(entities);
//            entities.setEvaluationResult(evaluateResultVo.getResult());
//            entities.setCvalue(evaluateResultVo.getCvalue());
//            entities.setRvalue(evaluateResultVo.getRvalue());
//            entities.setVvalue(evaluateResultVo.getVvalue());
//            entities.setPHEQ(evaluateResultVo.getPHEQ());
//            entities.setIsUpToStandard(evaluateResultVo.getIsUpToStandard());
//            entities.setUpdateTime(new Timestamp(System.currentTimeMillis()));
//            yhDisasterRepository.save(entities);
//        }
//    }

    //    @Override
//    public Map<String, String> evaluateRpheq(RpheqVo rpheqVo) {
//        //1.参数校验
//        Map<String, String> hazardLevelResult = new HashMap<>();
//        if (rpheqVo == null || StringUtils.isEmpty(rpheqVo.getLevel()) || StringUtils.isEmpty(rpheqVo.getBearDisasterBodyType())) {
//            hazardLevelResult.put("error", "请选择区划级别和工程类别");
//            return hazardLevelResult;
//        }
//        String level = rpheqVo.getLevel();//省市区级别
//        String bearDisasterBodyType = rpheqVo.getBearDisasterBodyType();//承灾体类别
//        //2.判断承灾体类别
//        //承灾体类别 建筑类：bt 构筑物类：st  生命线：lt
//        if ("bt".equals(bearDisasterBodyType)) {
//            //String[] bts = {"老旧居民小区", "学校", "医院", "商业中心", "养老福利院"};
//            String[] bts = {"住宅", "大中小学校舍", "医疗卫生设施", "社会服务保障设施", "商业中心"};
//            rpheqVo.setProjectTypes(Arrays.asList(bts));
//        }
//        if ("st".equals(bearDisasterBodyType)) {
//            //String[] sts = {"危化品厂库", "水库大坝", "大型车站", "核电站", "其他民用核设施", "市政大型水厂"};
//            String[] sts = {"供水厂"};
//            rpheqVo.setProjectTypes(Arrays.asList(sts));
//        }
//        if ("lt".equals(bearDisasterBodyType)) {
//            //String[] lts = {"大型隧道", "大型桥梁", "市政大型桥梁", "市政供水主干线"};
//            String[] lts = {"市政桥梁"};
//            rpheqVo.setProjectTypes(Arrays.asList(lts));
//        }
//        List<YhDisasterEntity> npheqList = yhDisasterNativeRepository.queryRpheqByProjectType(rpheqVo);
//        if (CollectionUtils.isEmpty(npheqList)) {
//            hazardLevelResult.put("error", "所选区域没有数据，请选择有数据的区域重新评估隐患等级！");
//            return hazardLevelResult;
//        }
//        //过滤
//        List<YhDisasterEntity> newYhDisaster = new ArrayList<>();
//        if (rpheqVo.getXD() != null && rpheqVo.getYD() != null) {
//            for (YhDisasterEntity yhDisaster : npheqList) {
//                if (rpheqVo.getXD().contains(yhDisaster.getLatitude()) && rpheqVo.getYD().contains(yhDisaster.getLongitude())) {
//                    newYhDisaster.add(yhDisaster);
//                }
//            }
//            if (CollectionUtils.isEmpty(newYhDisaster)) {
//                hazardLevelResult.put("error", "在您选择得区域内没有符合条件得数据存在！");
//                return hazardLevelResult;
//            }
//        } else {
//            newYhDisaster = npheqList;
//        }
//        if (StringUtils.isEmpty(rpheqVo.getProvince())) {
//            Map<String, List<YhDisasterEntity>> provinceMaps = new HashMap<>();
//            for (YhDisasterEntity provinceQh : newYhDisaster) {
//                List<YhDisasterEntity> value = provinceMaps.get(provinceQh.getProvince());
//                if (CollectionUtils.isEmpty(value)) {
//                    List<YhDisasterEntity> yhList = new ArrayList<>();
//                    yhList.add(provinceQh);
//                    provinceMaps.put(provinceQh.getProvince(), yhList);
//                } else {
//                    value.add(provinceQh);
//                    provinceMaps.put(provinceQh.getProvince(), value);
//                }
//            }
//            for (String province : provinceMaps.keySet()) {
//                List<YhDisasterEntity> provinceDisasterList = provinceMaps.get(province);
//                String cityHazardLevel = countHazardLevel(provinceDisasterList);
//                hazardLevelResult.put(province, cityHazardLevel);
//            }
//        }
//        /**
//         *  省区划：p 市：c  县：a
//         */
//        if ("p".equals(level) && StringUtils.isNotEmpty(rpheqVo.getProvince())) {//如果选择省，和省级区划，整个省为一个颜色
//            hazardLevelResult.put(rpheqVo.getProvince(), countHazardLevel(newYhDisaster));
//        }
//        if ("c".equals(level) && StringUtils.isEmpty(rpheqVo.getCity())) {
//            Map<String, List<YhDisasterEntity>> cityMaps = new HashMap<>();
//            for (YhDisasterEntity cityQh : newYhDisaster) {
//                List<YhDisasterEntity> value = cityMaps.get(cityQh.getCity());
//                if (CollectionUtils.isEmpty(value)) {
//                    List<YhDisasterEntity> yhList = new ArrayList<>();
//                    yhList.add(cityQh);
//                    cityMaps.put(cityQh.getCity(), yhList);
//                } else {
//                    value.add(cityQh);
//                    cityMaps.put(cityQh.getCity(), value);
//                }
//            }
//            for (String city : cityMaps.keySet()) {
//                List<YhDisasterEntity> cityDisasterList = cityMaps.get(city);
//                String cityHazardLevel = countHazardLevel(cityDisasterList);
//                hazardLevelResult.put(city, cityHazardLevel);
//            }
//        }
//        if ("a".equals(level) && StringUtils.isEmpty(rpheqVo.getCity())) {
//            Map<String, List<YhDisasterEntity>> cityMaps = new HashMap<>();
//            for (YhDisasterEntity cityQh : newYhDisaster) {
//                List<YhDisasterEntity> value = cityMaps.get(cityQh.getCity());
//                if (CollectionUtils.isEmpty(value)) {
//                    List<YhDisasterEntity> yhList = new ArrayList<>();
//                    yhList.add(cityQh);
//                    cityMaps.put(cityQh.getCity(), yhList);
//                } else {
//                    value.add(cityQh);
//                    cityMaps.put(cityQh.getCity(), value);
//                }
//            }
//            Map<String, List<YhDisasterEntity>> areaMaps = new HashMap<>();
//            for (String city : cityMaps.keySet()) {
//                for (YhDisasterEntity areaQh : cityMaps.get(city)) {
//                    List<YhDisasterEntity> value = areaMaps.get(city + "," + areaQh.getArea());
//                    if (CollectionUtils.isEmpty(value)) {
//                        List<YhDisasterEntity> yhList = new ArrayList<>();
//                        yhList.add(areaQh);
//                        areaMaps.put(city + "," + areaQh.getArea(), yhList);
//                    } else {
//                        value.add(areaQh);
//                        areaMaps.put(city + "," + areaQh.getArea(), value);
//                    }
//                }
//            }
//            for (String area : areaMaps.keySet()) {
//                List<YhDisasterEntity> areaDisasterList = areaMaps.get(area);
//                String areaHazardLevel = countHazardLevel(areaDisasterList);
//                hazardLevelResult.put(area, areaHazardLevel);
//            }
//        }
//        if ("c".equals(level) && StringUtils.isNotEmpty(rpheqVo.getCity())) {
//            hazardLevelResult.put(rpheqVo.getCity(), countHazardLevel(newYhDisaster));
//        }
//        if ("a".equals(level) && StringUtils.isNotEmpty(rpheqVo.getCity()) && StringUtils.isEmpty(rpheqVo.getArea())) {
//            Map<String, List<YhDisasterEntity>> area1Maps = new HashMap<>();
//            for (YhDisasterEntity areaQh : newYhDisaster) {
//                List<YhDisasterEntity> value = area1Maps.get(areaQh.getArea());
//                if (CollectionUtils.isEmpty(value)) {
//                    List<YhDisasterEntity> yhList = new ArrayList<>();
//                    yhList.add(areaQh);
//                    area1Maps.put(areaQh.getArea(), yhList);
//                } else {
//                    value.add(areaQh);
//                    area1Maps.put(areaQh.getArea(), value);
//                }
//            }
//            for (String area : area1Maps.keySet()) {
//                List<YhDisasterEntity> areaDisasterList = area1Maps.get(area);
//                String areaHazardLevel = countHazardLevel(areaDisasterList);
//                hazardLevelResult.put(rpheqVo.getCity() + "," + area, areaHazardLevel);
//            }
//        }
//        if (StringUtils.isNotEmpty(rpheqVo.getArea())) {
//            hazardLevelResult.put(rpheqVo.getCity() + "," + rpheqVo.getArea(), countHazardLevel(newYhDisaster));
//        }
//        return hazardLevelResult;
//    }
    @Override
    public Map<String, String> evaluateRpheq(RpheqVo rpheqVo) {
        //1.参数校验
        Map<String, String> hazardLevelResultAll = new HashMap<>();
        Map<String, String> hazardLevelResult = new HashMap<>();
        if (StringUtils.isEmpty(rpheqVo.getProvince())) {
            hazardLevelResult.put("error", "请选择省信息");
            return hazardLevelResult;
        }
        if (rpheqVo == null || StringUtils.isEmpty(rpheqVo.getLevel()) || StringUtils.isEmpty(rpheqVo.getBearDisasterBodyType())) {
            hazardLevelResult.put("error", "请选择区划级别和工程类别");
            return hazardLevelResult;
        }
        String level = rpheqVo.getLevel();//省市区级别
        String bearDisasterBodyType = rpheqVo.getBearDisasterBodyType();//承灾体类别
        //2.判断承灾体类别
        //承灾体类别 建筑类：bt 构筑物类：st  生命线：lt
        // if ("bt".equals(bearDisasterBodyType)) {
        //     //String[] bts = {"老旧居民小区", "学校", "医院", "商业中心", "养老福利院"};
        //     String[] bts = {"住宅", "大中小学校舍", "医疗卫生设施", "社会服务保障设施", "商业中心"};
        //     rpheqVo.setProjectTypes(Arrays.asList(bts));
        // }
        // if ("st".equals(bearDisasterBodyType)) {
        //     //String[] sts = {"危化品厂库", "水库大坝", "大型车站", "核电站", "其他民用核设施", "市政大型水厂"};
        //     String[] sts = {"供水厂"};
        //     rpheqVo.setProjectTypes(Arrays.asList(sts));
        // }
        // if ("lt".equals(bearDisasterBodyType)) {
        //     //String[] lts = {"大型隧道", "大型桥梁", "市政大型桥梁", "市政供水主干线"};
        //     String[] lts = {"市政桥梁"};
        //     rpheqVo.setProjectTypes(Arrays.asList(lts));
        // }
        List<YhDisasterEntity> npheqListAll =new ArrayList<>();
        List<YhDisasterEntity> npheqList = null;
        if ("F".equals(bearDisasterBodyType) || "G".equals(bearDisasterBodyType)) {
            npheqList = yhDisasterNativeRepository.queryRpheqByProjectType(rpheqVo,13);
        } else {
            // if ("山东省".equals(rpheqVo.getProvince())&&StringUtils.isNotEmpty(rpheqVo.getCity())){
            //     for (int i=1;i<4;i++) {
            //         System.out.println("------------当前位置：{}"+i);
            //         npheqList = yhDisasterNativeRepository.queryRpheqByProjectType(rpheqVo,i);
            //         npheqListAll.addAll(npheqList);
            //         npheqList.clear();
            //     }
            // }else {
            //     npheqList = yhDisasterNativeRepository.queryRpheqByProjectType(rpheqVo,0);
            // }
            npheqList = yhDisasterNativeRepository.queryRpheqByProjectType(rpheqVo,0);
        }
        if (npheqList.size()!=0) {
            npheqListAll.addAll(npheqList);
            npheqList.clear();
        }
        if (CollectionUtils.isEmpty(npheqListAll)) {
            hazardLevelResult.put("error", "所选区域没有数据，请选择有数据的区域重新评估隐患等级！");
            return hazardLevelResult;
        }
        //过滤
        List<YhDisasterEntity> newYhDisaster = new ArrayList<>();
        if (rpheqVo.getXD() != null && rpheqVo.getYD() != null) {
            for (YhDisasterEntity yhDisaster : npheqListAll) {
                if (rpheqVo.getXD().contains(yhDisaster.getLatitude()) && rpheqVo.getYD().contains(yhDisaster.getLongitude())) {
                    newYhDisaster.add(yhDisaster);
                }
            }
            if (CollectionUtils.isEmpty(newYhDisaster)) {
                hazardLevelResult.put("error", "在您选择得区域内没有符合条件得数据存在！");
                return hazardLevelResult;
            }
        } else {
            newYhDisaster = npheqListAll;
        }
        if (StringUtils.isEmpty(rpheqVo.getProvince())) {
            Map<String, List<YhDisasterEntity>> provinceMaps = new HashMap<>();
            for (YhDisasterEntity provinceQh : newYhDisaster) {
                List<YhDisasterEntity> value = provinceMaps.get(provinceQh.getProvince());
                if (CollectionUtils.isEmpty(value)) {
                    List<YhDisasterEntity> yhList = new ArrayList<>();
                    yhList.add(provinceQh);
                    provinceMaps.put(provinceQh.getProvince(), yhList);
                } else {
                    value.add(provinceQh);
                    provinceMaps.put(provinceQh.getProvince(), value);
                }
            }
            for (String province : provinceMaps.keySet()) {
                List<YhDisasterEntity> provinceDisasterList = provinceMaps.get(province);
                String cityHazardLevel = countHazardLevel(provinceDisasterList);
                hazardLevelResult.put(province, cityHazardLevel);
            }
        }
        /**
         *  省区划：p 市：c  县：a
         */
        if ("p".equals(level) && StringUtils.isNotEmpty(rpheqVo.getProvince())) {//如果选择省，和省级区划，整个省为一个颜色
            hazardLevelResult.put(rpheqVo.getProvince(), countHazardLevel(newYhDisaster));
        }
        if ("c".equals(level) && StringUtils.isEmpty(rpheqVo.getCity())) {
            Map<String, List<YhDisasterEntity>> cityMaps = new HashMap<>();
            for (YhDisasterEntity cityQh : newYhDisaster) {
                List<YhDisasterEntity> value = cityMaps.get(cityQh.getCity());
                if (CollectionUtils.isEmpty(value)) {
                    List<YhDisasterEntity> yhList = new ArrayList<>();
                    yhList.add(cityQh);
                    cityMaps.put(cityQh.getCity(), yhList);
                } else {
                    value.add(cityQh);
                    cityMaps.put(cityQh.getCity(), value);
                }
            }
            for (String city : cityMaps.keySet()) {
                List<YhDisasterEntity> cityDisasterList = cityMaps.get(city);
                String cityHazardLevel = countHazardLevel(cityDisasterList);
                hazardLevelResult.put(city, cityHazardLevel);
            }
        }
        if ("a".equals(level) && StringUtils.isEmpty(rpheqVo.getCity())) {
            Map<String, List<YhDisasterEntity>> cityMaps = new HashMap<>();
            for (YhDisasterEntity cityQh : newYhDisaster) {
                List<YhDisasterEntity> value = cityMaps.get(cityQh.getCity());
                if (CollectionUtils.isEmpty(value)) {
                    List<YhDisasterEntity> yhList = new ArrayList<>();
                    yhList.add(cityQh);
                    cityMaps.put(cityQh.getCity(), yhList);
                } else {
                    value.add(cityQh);
                    cityMaps.put(cityQh.getCity(), value);
                }
            }
            Map<String, List<YhDisasterEntity>> areaMaps = new HashMap<>();
            for (String city : cityMaps.keySet()) {
                for (YhDisasterEntity areaQh : cityMaps.get(city)) {
                    List<YhDisasterEntity> value = areaMaps.get(city + "," + areaQh.getArea());
                    if (CollectionUtils.isEmpty(value)) {
                        List<YhDisasterEntity> yhList = new ArrayList<>();
                        yhList.add(areaQh);
                        areaMaps.put(city + "," + areaQh.getArea(), yhList);
                    } else {
                        value.add(areaQh);
                        areaMaps.put(city + "," + areaQh.getArea(), value);
                    }
                }
            }
            for (String area : areaMaps.keySet()) {
                List<YhDisasterEntity> areaDisasterList = areaMaps.get(area);
                String areaHazardLevel = countHazardLevel(areaDisasterList);
                hazardLevelResult.put(area, areaHazardLevel);
            }
        }
        if ("c".equals(level) && StringUtils.isNotEmpty(rpheqVo.getCity())) {
            hazardLevelResult.put(rpheqVo.getCity(), countHazardLevel(newYhDisaster));
        }
        if ("a".equals(level) && StringUtils.isNotEmpty(rpheqVo.getCity()) && StringUtils.isEmpty(rpheqVo.getArea())) {
            System.out.println("------开始解析：{}");
            Map<String, List<YhDisasterEntity>> area1Maps = new HashMap<>();
            for (YhDisasterEntity areaQh : newYhDisaster) {
                List<YhDisasterEntity> value = area1Maps.get(areaQh.getArea());
                if (CollectionUtils.isEmpty(value)) {
                    List<YhDisasterEntity> yhList = new ArrayList<>();
                    yhList.add(areaQh);
                    area1Maps.put(areaQh.getArea(), yhList);
                } else {
                    value.add(areaQh);
                    area1Maps.put(areaQh.getArea(), value);
                }
            }
            for (String area : area1Maps.keySet()) {
                List<YhDisasterEntity> areaDisasterList = area1Maps.get(area);
                String areaHazardLevel = countHazardLevel(areaDisasterList);
                hazardLevelResult.put(rpheqVo.getCity() + "," + area, areaHazardLevel);
            }
        }
        if (StringUtils.isNotEmpty(rpheqVo.getArea())) {
            hazardLevelResult.put(rpheqVo.getCity() + "," + rpheqVo.getArea(), countHazardLevel(newYhDisaster));
        }
        hazardLevelResultAll.putAll(hazardLevelResult);
        hazardLevelResult.clear();
        return hazardLevelResultAll;
    }

    /**
     * 计算隐患等级通用方法
     *
     * @param newYhDisaster
     * @return
     */
    public String countHazardLevel(List<YhDisasterEntity> newYhDisaster) {

        //List<YhDisasterEntity> allNDataList = yhDisasterNativeRepository.queryRpheq(rpheqVo);
        Double N = 0.0;
        Double NPHEQ1 = 0.0000;
        Double NPHEQ2 = 0.0000;
        Double NPHEQ3 = 0.0000;
        for (YhDisasterEntity npheqData : newYhDisaster) {
            String constructionScale = npheqData.getYhConstructionScale();//建设规模
            Double constructionScaleNum = CharTypeUtil.separateNum(constructionScale);
            N += constructionScaleNum;
            if("轻微".equals(npheqData.getEvaluationResult())){//评估结果 i=2
                NPHEQ1+=constructionScaleNum;
            }
            if ("一般".equals(npheqData.getEvaluationResult())) {//评估结果 i=2
                NPHEQ2 += constructionScaleNum;
            }
            if ("重点".equals(npheqData.getEvaluationResult())) {//评估结果 i=3
                NPHEQ3 += constructionScaleNum;
            }
        }
        //计算 RPHEQi=NPHEQi/N;
        // Double RPHEQ1 = NPHEQ1/N;
        Double RPHEQ1 = 0.0;
        Double RPHEQ2 = 0.0;
        Double RPHEQ3 = 0.0;
        if (NPHEQ1 != 0.0 && N != 0.0) {
            RPHEQ1 = NPHEQ1 / N;
        }
        if (NPHEQ2 != 0.0 && N != 0.0) {
            RPHEQ2 = NPHEQ2 / N;
        }
        if (NPHEQ3 != 0.0 && N != 0.0) {
            RPHEQ3 = NPHEQ3 / N;
        }

        /**
         * 隐患指数RPHEQ3=0且RPHEQ2<0.1时，隐患等级为：轻微
         * 隐患指数0<RPHEQ3<0.1或0.1<=RPHEQ2<0.5时，隐患等级为：一般0 < 𝑅𝐼𝑃𝑬𝐻3 < 0.1和/或0.1 ≤ 𝑅𝐼𝑃𝑬𝐻2 + 𝑅𝐼𝑃𝑬𝐻3 < 0.5
         * 隐患指数RPHEQ3=>0.1或RPHEQ2>0.5时，隐患等级为：重点======𝑅𝑃𝐻𝐸𝑄3 ≥ 0.1和/或𝑅𝑃𝐻𝐸𝑄3 + 𝑅𝑃𝐻𝐸𝑄2 ≥ 0.5
         *
         */
        String RPHEQResult = null;//隐患等级
        /*if (RPHEQ3 == 0 && RPHEQ2 < 0.1) {
            RPHEQResult = "轻微";
        }
        if ((0 < RPHEQ3 && RPHEQ3 < 0.1) || (0.1 <= (RPHEQ2 + RPHEQ3) && (RPHEQ2 + RPHEQ3) < 0.5)) {
            RPHEQResult = "一般";
        }
        if (0.1 <= RPHEQ3 || (RPHEQ2 + RPHEQ3) >= 0.5) {
            RPHEQResult = "重点";
        }*/
        if (RPHEQ3<=0.01&&RPHEQ1>=0.9){
            RPHEQResult = "轻微";
        }else if (RPHEQ3>=0.1||(RPHEQ2 + RPHEQ3) >= 0.5){
            RPHEQResult = "重点";
        }else {
            RPHEQResult = "一般";
        }
        return RPHEQResult;
    }


    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public int saveDisasterList(List<YhDisasterVO> list, StringBuilder message) {
        int count = 0;
        for (int i = 0; i < list.size(); i++) {
            YhDisasterEntity yhDisasterEntity = new YhDisasterEntity();
            YhDisasterVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            String isValid = "1";
            // 根据样本编号判断重复导入性
            List<YhDisasterEntity> yhDisasterEntityList = yhDisasterRepository.findByYhCodeAndIsValid(yhDisasterVO.getYhCode(), isValid);
            if (yhDisasterEntityList.size() == 0) {
                message.append("业务主键" + yhDisasterVO.getYhCode() + "不存在，请查看是否修改");
                ++count;
            } else {
                updateYhDisaster(yhDisasterEntity);
            }
        }
        return count;
    }

    /**
     * 承载体地震灾害隐患指数
     * 承灾体单体的地震灾害隐患指数确定应综合考虑 承灾体的地震易损性、所处场址的地震
     * 危险性及其在遭受地震破坏时所产生后果的严重程度三方面，
     *
     * @param disasterEntity
     * @return
     */
    public EvaluateResultVo pgResult(YhDisasterEntity disasterEntity) {
        if (disasterEntity == null) {
            return null;
        }
        //场地类型
        String yhFieldType = disasterEntity.getYhFieldType();
        //现抗震设防烈度
        String yhNowEarthQh = disasterEntity.getYhNowEarthQh();
        //原抗震设防烈度
        String yhEarthIntensity = disasterEntity.getYhEarthIntensity();
        //建筑年代
        String yhBuildingTime = disasterEntity.getYhBuildingTime();
        //现存灾害
        String yhExistingVirus = disasterEntity.getYhExistingVirus();
        //抗震设防类别
        String yhEarthFortification = disasterEntity.getYhEarthFortification();
        //建筑规模大小
        String yhConstructionScale = disasterEntity.getYhConstructionScale();
        Double scaleSize = 0.0;
        if (StringUtils.isNotEmpty(yhConstructionScale)) {
            scaleSize = Double.valueOf(yhConstructionScale);
        }
        //1.承灾体破坏后果影响系数值计算
        Double C = 0.0;//改为抗震设防类别
        if ("I类（甲类）".equals(yhEarthFortification)) {
            C = 0.3;
        }
        if ("II类（乙类）".equals(yhEarthFortification)) {
            C = 0.35;
        }
        if ("III类（丙类）".equals(yhEarthFortification)) {
            if (scaleSize > 500) {
                C = 0.4;
            } else {
                C = 0.5;
            }
        }
        if ("IV类（丁类）".equals(yhEarthFortification)) {
            C = 1.0;
        }
        //2.承灾体相应地震危险性系数值计算
        Double R1 = 0.0;//现抗震设防烈度
        Double R2 = 0.0;//场地类别
        Double aR = 0.5;//权重
        Double bR = 0.5;
        //2.1 计算R1:地震危险性的场址影响系数
        if ("6度".equals(yhNowEarthQh)) {//0.05g
            R1 = 1.0;
        }
        if ("7度（0.1g）".equals(yhNowEarthQh) || "7度（0.15g）".equals(yhNowEarthQh)) {
            R1 = 0.95;
        }
        if ("8度（0.2g）".equals(yhNowEarthQh) || "8度（0.3g）".equals(yhNowEarthQh)) {
            R1 = 0.9;
        }
        if ("9度".equals(yhNowEarthQh)) {//0.40
            R1 = 0.85;
        }
        //2.2 计算R2:场地类别的场址影响系数
        if (CommonConstant.FIELDTYPE_Ⅰ.equals(yhFieldType)) {
            R2 = 1.0;
        }
        if (CommonConstant.FIELDTYPE_Ⅱ.equals(yhFieldType)) {
            R2 = 0.95;
        }
        if (CommonConstant.FIELDTYPE_Ⅲ.equals(yhFieldType)) {
            R2 = 0.9;
        }
        if (CommonConstant.FIELDTYPE_Ⅳ.equals(yhFieldType)) {
            R2 = 0.85;
        }
        if (CommonConstant.FIELDTYPE_Ⅴ.equals(yhFieldType)) {
            R2 = 0.75;
        }
        //承灾体场址影响系数:R
        Double R = aR * R1 + bR * R2;

        //3. 承灾体详细情况值计算
        Double V1 = 0.0;//承灾体抗震设防情况
        Double V2 = 0.0;//承灾体建造年代情况
        Double V3 = 0.0; //承灾体病害情况
        Double aV = 0.6;
        Double bV = 0.1;
        Double cV = 0.3;
        //3.1 V1计算
        Double yhEarthIntensityNum = subStr(yhEarthIntensity);
        Double yhNowEarthQhNum = subStr(yhNowEarthQh);
        if (yhEarthIntensityNum > yhNowEarthQhNum) {
            V1 = 1.0;
        } else if (yhEarthIntensityNum.equals(yhNowEarthQhNum)) {
            V1 = 0.8;
        } else if ((yhEarthIntensityNum == 7.1 && yhNowEarthQhNum == 7.15) ||
                (yhEarthIntensityNum == 7.15 && yhNowEarthQhNum == 8.2) ||
                (yhEarthIntensityNum == 8.2 && yhNowEarthQhNum == 8.3)) {
            V1 = 0.4;
        } else if ((yhNowEarthQhNum - yhEarthIntensityNum >= 1) ||
                (yhEarthIntensityNum == 0.0 && yhNowEarthQhNum == 6)) {
            V1 = 0.2;
        } else {
            V1 = 0.1;
        }
        //V2计算
        if ("不清楚".equals(yhBuildingTime) || "1989年以前".equals(yhBuildingTime)) {
            V2 = 0.7;
        } else if ("1990年代".equals(yhBuildingTime)) {
            V2 = 0.85;
        } else if ("2000年代".equals(yhBuildingTime)) {
            V2 = 0.95;
        } else if ("2011年以后".equals(yhBuildingTime)) {
            V2 = 1.0;
        }

        //V3计算
        if (StringUtils.isEmpty(yhExistingVirus)) {
            V3 = 1.0;
        } else if ("无".equals(yhExistingVirus)) {
            V3 = 1.0;
        } else if ("轻微".equals(yhExistingVirus)) {
            V3 = 0.95;
        } else if ("一般".equals(yhExistingVirus)) {
            V3 = 0.70;
        } else if ("较大".equals(yhExistingVirus)) {
            V3 = 0.30;
        } else if ("严重".equals(yhExistingVirus)) {
            V3 = 0.0;//==0.10->0
        }
        //承灾体易损性影响系数:V -包含承灾体设防标准、建造年代和承灾体病害
        Double V = aV * V1 + bV * V2 + cV * V3;
        /**
         * 隐患指数DEH在(0.225~1.0]范围内时，隐患等级为：轻微
         * 隐患指数DEH在(0.075, 0.225]范围内时，隐患等级为：一般
         * 隐患指数DEH在(0, 0.075]范围内时，隐患等级为：重点
         */
        Double DEH = C * R * V;
        int is = 0;
        String result = "";
        if (0 < DEH && DEH <= 0.075) {
            result = "重点";
        } else if (0.075 < DEH && DEH <= 0.225) {
            result = "一般";
        } else if (0.225 < DEH && DEH <= 1.0) {
            result = "轻微";
            is = 1;
        }
        EvaluateResultVo evaluateResultVo = new EvaluateResultVo();
        evaluateResultVo.setCvalue(C);
        evaluateResultVo.setRvalue(R);
        evaluateResultVo.setVvalue(V);
        evaluateResultVo.setPHEQ(DEH);
        evaluateResultVo.setIsUpToStandard(is);
        evaluateResultVo.setResult(result);
        return evaluateResultVo;
    }

    /**
     * 截取数值
     *
     * @param str
     * @return
     */
    public Double subStr(String str) {
        if (str.contains("度")) {
            Double integer = Double.valueOf(str.split("度")[0]);
            if ("6度".equals(str)) {
                return integer;
            } else if ("7度（0.1g）".equals(str)) {
                Double sub = sub(str);
                return integer + sub;
            } else if ("7度（0.15g）".equals(str)) {
                Double sub = subOther(str);
                return integer + sub;
            } else if ("8度（0.2g）".equals(str)) {
                Double sub = sub(str);
                return integer + sub;
            } else if ("8度（0.3g）".equals(str)) {
                Double sub = sub(str);
                return integer + sub;
            } else if ("9度".equals(str)) {
                return integer;
            }
        }
        return 0.0;
    }

    /**
     * 截取 2度（0.2）获得0.2
     *
     * @param str
     * @return
     */
    public Double sub(String str) {
        String a = str.split("度")[1].substring(1, 4);
        Double b = Double.valueOf(a);
        return b;
    }

    /**
     * 截取0.01g获取0.01
     *
     * @param str
     * @return
     */
    public Double subOther(String str) {
        String a = str.split("度")[1].substring(1, 5);
        Double b = Double.valueOf(a);
        return b;
    }

    @Override
    public void exportDisasterEvaluation(ExportDisasterEvaluateParams queryParams, HttpServletResponse response) {
        long exportStart = System.currentTimeMillis();
        String yhProjectType = queryParams.getYhProjectType();
        ExportParams exportParams = new ExportParams(yhProjectType + "评估结果", yhProjectType + "评估结果");
        Workbook workbook = ExcelExportUtil.exportBigExcel(exportParams, DisasterEvaluateVO.class, disasterEvaluationExportServer, queryParams);
        EasyPoiExcelUtil.downLoadExcel(exportParams.getTitle() + ".xlsx", response, workbook);
        logger.info("生成导出文件耗时：{}", System.currentTimeMillis() - exportStart);
    }


    @Autowired
    private BoundaryService boundaryService;

    @Override
    public void exportEvaluateRpheqResult(RpheqVo rpheqVo, HttpServletResponse response) {

        List<ExcelDataVo> excelDataVos = new ArrayList<>();
        String province = rpheqVo.getProvince(), city = rpheqVo.getCity(), areas = rpheqVo.getArea(), code = "";

        if (PlatformObjectUtils.isEmpty(province) || PlatformObjectUtils.isEmpty(city) || PlatformObjectUtils.isEmpty(areas)) {
            EasyPoiExcelUtil.exportExcel(excelDataVos, "隐患等级数据", "隐患等级数据", ExcelDataVo.class, "隐患等级数据.xls", response);
            return;
        }

        Map<String, String> code2name = boundaryService.listAreaCode2NameByProvinceAndCity(province, city, null, "1");
        for (Map.Entry<String, String> entityI : code2name.entrySet()) {

            code = entityI.getKey();
            String area = entityI.getValue();
            if (areas.indexOf(area) == -1) continue;

            rpheqVo.setArea(area);
            rpheqVo.setLevel("a");
            Map<String, String> hazardLevelResult = evaluateRpheq(rpheqVo);
            if (hazardLevelResult.get("error") == null) {
                for (Map.Entry<String, String> entityJ : hazardLevelResult.entrySet()) {
                    String value = entityJ.getValue();

                    ExcelDataVo excelDataVo = new ExcelDataVo();
                    excelDataVo.setProvince(province);
                    excelDataVo.setCity(city);
                    excelDataVo.setArea(area);
                    excelDataVo.setCode(code);
                    excelDataVo.setLevel(value);

                    excelDataVos.add(excelDataVo);
                }
            }

        }
        String excelFileName = "隐患等级数据(" + province + city + ")";
        EasyPoiExcelUtil.exportExcel(excelDataVos, excelFileName, "隐患等级数据", ExcelDataVo.class, excelFileName + ".xls", response);
    }

    @Override
    public List<ExcelDataVo> searchEvaluateRpheqResult(RpheqVo rpheqVo) {
        List<ExcelDataVo> excelDataVos = new ArrayList<>();
        String province = rpheqVo.getProvince(), city = rpheqVo.getCity(), area = rpheqVo.getArea(), code = "";

        if (PlatformObjectUtils.isEmpty(province) || PlatformObjectUtils.isEmpty(city)) return excelDataVos;

        Map<String, String> code2name = boundaryService.listAreaCode2NameByProvinceAndCity(province, city, area, "1");
        for (Map.Entry<String, String> entityI : code2name.entrySet()) {

            code = entityI.getKey();
            area = entityI.getValue();

            rpheqVo.setArea(area);
            rpheqVo.setLevel("a");
            Map<String, String> hazardLevelResult = evaluateRpheq(rpheqVo);
            if (hazardLevelResult.get("error") == null) {
                for (Map.Entry<String, String> entityJ : hazardLevelResult.entrySet()) {
                    String value = entityJ.getValue();

                    ExcelDataVo excelDataVo = new ExcelDataVo();
                    excelDataVo.setProvince(province);
                    excelDataVo.setCity(city);
                    excelDataVo.setArea(area);
                    excelDataVo.setCode(code);
                    excelDataVo.setLevel(value);

                    excelDataVos.add(excelDataVo);
                }
            }

        }
        return excelDataVos;
    }
}
